var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require('express-session');
const useRouter = require('./routes');

const error = require('./middleware/error');
const { verifyToken } = require('./middleware/auth');
const { secretKey } = require('./config');
const { RedisStore } = require('connect-redis');
const client = require('./redis');
const { fileInit } = require('./middleware/files');
const { joiConfig } = require('./middleware/joi');
client.select(8);

var app = express();

// 使用第三方中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// session
app.use(
	session({
		secret: secretKey,
		name: 'sessionId',
		resave: true, // 强制保存到仓库
		saveUninitialized: false, // 没有用过的session要不要保存
		cookie: {
			// session 内部也是需要通过cookie实现的
			maxAge: 60 * 60 * 1000,
			base: '/',
			domain: 'localhost'
		},
		// 如果不用仓库，存在内存，数据一会就丢失了
		store: new RedisStore({
			client: client,
			prefix: 'sessionLogin:'
		})
	})
);

// 文件中间件
app.use(fileInit);

// token校验
app.use(verifyToken());

// 参数校验
app.use(joiConfig);

// 引入数据库
require('./models/sync');

// 路由设置
useRouter(app);

// 都没有匹配
app.use(function (req, res, next) {
	next(createError(404));
});

// 错误中间件
app.use(error());

module.exports = app;
